package com.yusvn.scm.admin.controller;

import java.util.ArrayList;
import java.util.List;

import com.alibaba.fastjson.JSONObject;
import com.jfinal.aop.Clear;
import com.jfinal.aop.Inject;
import com.jfinal.ext.cors.EnableCORS;
import com.jfinal.json.FastJson;
import com.jfinal.kit.Kv;
import com.jfinal.kit.StrKit;
import com.yusvn.scm.admin.auth.AdminAuthInterceptor;
import com.yusvn.scm.admin.service.AdminMenuService;
import com.yusvn.scm.admin.service.AdminRoleService;
import com.yusvn.scm.admin.service.AdminUserService;
import com.yusvn.scm.common.BaseController;
import com.yusvn.scm.common.kit.RetKit;
import com.yusvn.scm.common.model.SysMenu;
import com.yusvn.scm.common.model.SysUser;

/**
 * 后台主页
 * @author liugz
 *
 */
@EnableCORS
public class MainController extends BaseController {

	@Inject
	AdminUserService userSrv;
	
	@Inject
	AdminMenuService menuSrv;

	@Inject
	AdminRoleService roleSrv;
	
	
	public void index() {
		renderJson();
	}
	
	/**
	 * 获取登录用户菜单
	 */
	@Clear({AdminAuthInterceptor.class})
	public void menu() {
		List<SysMenu> userMenu = menuSrv.getUserMenu(getLoginUserId(), SysMenu.TYPE_MENU);
		
		//使用MixedJsonFactory时，如果数据中有子对象，需要用FastJson转换下
		//renderJson(FastJson.getJson().toJson( RetKit.ok().setData( menuSrv.toMenuTree(userMenu, 0)) ));
		renderJson(RetKit.ok().setData( JSONObject.toJSON(menuSrv.toMenuTree(userMenu, 0)) ) );
	}
	
	/**
	 * 获取登录用户信息
	 */
	@Clear({AdminAuthInterceptor.class})
	public void user() {
		SysUser user = getLoginUser();
		
		//用户权限
		List<SysMenu> menus = menuSrv.getUserMenu(getLoginUserId());
		//排除null
		List<SysMenu> authList = new ArrayList<>();
        for (SysMenu menu : menus) {
            if (StrKit.notBlank(menu.getAuthority())) {
                authList.add(menu);
            }
        }
		user.setAuthorities(authList);
		
		//用户角色
		user.setRoles(roleSrv.getUserRole(getLoginUserId()) );
		
		//renderJson(FastJson.getJson().toJson( RetKit.ok().setData( user ) ));
		renderJson(RetKit.ok().setData( JSONObject.toJSON(user) ));
		
	}
	
	/**
	 * 修改密码
	 */
	@Clear({AdminAuthInterceptor.class})
	public void password() {
		Kv kv = FastJson.getJson().parse(getRawData(), Kv.class);
		//System.out.println(" 改密kv:"+kv);
		
		kv.set("userId", getLoginUserId());
		
		renderJson(userSrv.updatePassword(kv));
	}
	

}


